a set of tutorials by The Coding Train on Youtube
First of all, you should know that all the documentation is on TF’s website, under the API Reference section.
But wait, why is it called TensorFlow? What even is a tensor?A tensor is basically a structure of numbers.
In TF, tensors are differentiated because of their rank, or, in other words, the number of dimensions they have.
These are the most common ones:
Just a number.
This is how you can create and console-log one:
→ tf.scalar(4.5).print();
And the output is the following:
Tensor
4.5
These are higher dimensional tensors.
If you wanted to create a rank-1 tensor, for instance, you could simply do:
→ tf.tensor1d([3, 7, 8]).print();
Which would output:
Tensor
[3, 7, 8]
If you don’t know the dimensions of your tensor, you can simply create one with the following function (notice how the above two examples work just as well with this other method):
→ tf.tensor(4.5).print();
tf.tensor([3, 7, 8]).print();
This outputs exactly the same as before.
You can, additionally, pass a couple more parameters to these functions.
→ tf.tensor(values, shape?, dtype?)
Let’s look at
values first.
This is the only compulsory parameter, and the only one we’ve been passing on in the previous examples.
You can either pass a flat array of values (or even a single number in scalars) and specify the shape yourself, or you can pass a nested array.
Now you might be wondering what
shape is.
So, let’s say you want to output the following tensor:
[[1, 5],
[4, 7]]
That is, you guessed right, a 2x2 matrix.
You can either create this tensor by passing a flat array and specifying the shape as the second parameter of the function
tf.tensor([1, 5, 4, 7], [2, 2]).print();
or by passing a nested array
tf.tensor([[1, 5], [4, 7]]).print();
Lastly, we have
dtype.
This specifies the data type.
As for now,
int32, float32 and
bool are the three supported types.
But, what can you do with these tensors? Well, among other things, you can perform mathematical computation on them, such as arithmetic operations:
Note: the following operations are performed element-wise, which means that every term of the first tensor involved is associated with the term in its same place in the other tensor.
const a = tf.tensor1d([4, 7, 2, 1]);
const b = tf.tensor1d([20, 30, 40, 50]);
There are two ways these two can be added:
→ a.add(b).print();
or,
→ tf.add(a, b);
Both output:
Tensor
[24, 37, 42, 51]
Here’s how they work for subtraction,
→ tf.sub(a, b).print();
Tensor //output
[-16, -23, -38, -49]
multiplication,
→ tf.mul(a, b).print();
Tensor //output
[80, 210, 80, 50]
and division:
→ tf.div(a, b).print();
Tensor //output
[0.2, 0.2333333, 0.05, 0.02]
It’s pretty simple and straightforward.